# -*- coding: utf-8 -*-

from datetime import datetime
from flask import request
from flask_restplus import Resource

from .security import require_auth
from . import api_rest

import io
import sys
import re
import requests
from bs4 import BeautifulSoup

class SecureResource(Resource):
    method_decorators = [require_auth]

    # sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8') # 编码


@api_rest.route('/resource/<string:resource_id>')
class ResourceOne(Resource):
    def get(self, resource_id):
        timestamp = datetime.utcnow().isoformat()
        return {'timestamp': timestamp}

    def post(self, resource_id):
        json_payload = request.json
        return {'timestamp': json_payload}, 201

@api_rest.route('/secure-resource/<string:resource_id>')
class SecureResourceOne(SecureResource):
    def get(self, resource_id):
        timestamp = datetime.utcnow().isoformat()
        return {'timestamp': timestamp}

# 百度
@api_rest.route('/phone-number/baidu/<string:phone_number>')
class PhoneNumberBaidu(SecureResource):
    def get(self, phone_number):
        html_doc = requests.get('http://www.baidu.com/s?ie=UTF-8&wd=' + phone_number)

        soup = BeautifulSoup(html_doc.content, 'html.parser')
        
        fraudphone = soup.find(tpl="fraudphone")

        if ( fraudphone ):
            fraudphone_label = fraudphone.find(name='span', attrs={"class": "op_fraudphone_label"})
            fraudphone_number = fraudphone.find(name='span', attrs={"class": "op_fraudphone_number"})
            fraudphone_addr = fraudphone.find(name='span', attrs={"class": "op_fraudphone_addr"})
            fraudphone_word = fraudphone.find(name='div', attrs={"class": "op_fraudphone_word"})
            
            result = {
                'code': 600,
                'data': {
                    'fraudphone_label': fraudphone_label.string,
                    'fraudphone_number': fraudphone_number.string,
                    'fraudphone_addr': fraudphone_addr.string,
                    'fraudphone_word': fraudphone_word.get_text().strip()
                }
            }
        else:
            result = {
                'code': 601
            }

        return result

# 搜狗
@api_rest.route('/phone-number/sogou/<string:phone_number>')
class PhoneNumberSogou(SecureResource):
    def get(self, phone_number):
        data = {}

        html_doc = requests.get('https://www.sogou.com/web?ie=utf8&_ast=1542175488&_asf=null&w=01029901&p=40040100&dp=1&cid=&s_from=result_up&query=' + phone_number)

        matchObj = re.match(r'[\s\S]*号码通用户数据：([^\']*)：[\s\S]*', html_doc.content.decode('utf-8'), re.M | re.I)
        if ( matchObj ):
            data['fraudphone_label'] = matchObj.group(1);

        matchObj = re.match(r'[\s\S]*tpl18139\(18139.*\',\'(.*?)\'\);[\s\S]*', html_doc.content.decode('utf-8'), re.M | re.I)
        if ( matchObj ):
            data['fraudphone_addr'] = matchObj.group(1);

        if ( data ):
            result = {
                'code': 600,
                'data': data
            }
        else:
            result = {
                'code': 601
            }

        return result

# 360
@api_rest.route('/phone-number/360/<string:phone_number>')
class PhoneNumber360(SecureResource):
    def get(self, phone_number):
        html_doc = requests.get('https://www.so.com/s?ie=utf-8&fr=none&src=360sou_newhome&q=' + phone_number)

        soup = BeautifulSoup(html_doc.content, 'html.parser')

        fraudphone = soup.find(name='div', attrs={"id": "mohe-mobilecheck"})

        if ( fraudphone ):
            data = {}

            fraudphone_temp = fraudphone.find(name='div', attrs={"class": "mh-detail"})
            if ( fraudphone_temp ):
                fraudphone_number = fraudphone_temp.select("span:nth-of-type(1)")
                fraudphone_addr = fraudphone_temp.select("span:nth-of-type(2)")
                
                if ( fraudphone_number ):
                    data['fraudphone_number'] = fraudphone_number[0].get_text().strip()
                if ( fraudphone_addr ):
                    data['fraudphone_addr'] = fraudphone_addr[0].get_text().strip()

            fraudphone_label = fraudphone.find(name='span', attrs={"class": "mohe-ph-mark"})
            fraudphone_word = fraudphone.select("div.mohe-tips > span:nth-of-type(2)");

            if ( fraudphone_label ):
                data['fraudphone_label'] = fraudphone_label.get_text().strip()
            if ( fraudphone_word ):
                data['fraudphone_word'] = fraudphone_word[0].get_text().strip()

        if ( data ):
            result = {
                'code': 600,
                'data': data
            }
        else:
            result = {
                'code': 601
            }

        return result

# 消标易
@api_rest.route('/phone-number/xiaobiaoyi/<string:phone_number>')
class PhoneNumberXiaoBiaoYi(SecureResource):
    def get(self, phone_number):
        html_doc = requests.get('https://www.biaojiquxiao.com/status/' + phone_number)

        json_doc = html_doc.json()

        data = []
        if ( json_doc ):
            soup = BeautifulSoup(json_doc['html'], 'html.parser')

            for tr in soup.find_all('tr'):
                temp = tr.find(name='td', attrs={"class": "enbold"})
                if ( temp ):
                    data.append(temp.get_text().strip())

        if ( data ):
            result = {
                'code': 600,
                'data': data
            }
        else:
            result = {
                'code': 601
            }

        return result
